/**
 * canvas文本超出范围时，自动换行
 * @param {*} ctx
 * @param {*} text
 * @param {*} x
 * @param {*} y
 * @param {*} maxWidth
 * @param {*} lineHeight
 */
export function canvasTextAutoLine(ctx, text, x, y, maxWidth, lineHeight) {
  let lineWidth = 0
  let lastSubStrIndex = 0
  for (let i = 0; i < text.length; i++) {
    lineWidth += ctx.measureText(text[i]).width
    if (lineWidth > maxWidth) {
      ctx.fillText(text.substring(lastSubStrIndex, i), x, y)
      y += lineHeight
      lineWidth = 0
      lastSubStrIndex = i
    }
    if (i === text.length - 1) {
      ctx.fillText(text.substring(lastSubStrIndex, i + 1), x, y)
    }
  }
}

// 时分秒(10:11:30) => 秒
export function timeToSec(time) {
	const timePartArr = time.split(':')
	if(timePartArr.length !== 3) return
	const hour = Number(timePartArr[0]) * 3600
	const min = Number(timePartArr[1]) * 60
	const second = Number(timePartArr[2])

	const result = hour + min + second
	if(Number.isNaN(result)) return 0
	return hour + min + second
}

export function getSourceFullPath(res) {
	if (/http|https/.test(res)) return res
	return getApp().globalData.img_url + res
}

export function randomString(strLen) {
	if(strLen < 0) {
		throw new Error('目标字符串长度异常')
	}

	const keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890abcdefghijklmnopqrstuvwxyz"
	let result = ''
	let keyLen = keyStr.length
	for(let i = 0; i< strLen; i++) {
		result += keyStr.charAt(Math.floor(Math.random()*keyLen))
	}

	return result
}
// 进行微信小程序基础库版本判断
export function compareVersion(_v1, _v2) {
  if (typeof _v1 !== 'string' || typeof _v2 !== 'string') return 0

  const v1 = _v1.split('.')
  const v2 = _v2.split('.')
  const len = Math.max(v1.length, v2.length)

  while (v1.length < len) {
    v1.push('0')
  }
  while (v2.length < len) {
    v2.push('0')
  }

  for (let i = 0; i < len; i++) {
    const num1 = parseInt(v1[i], 10)
    const num2 = parseInt(v2[i], 10)

    if (num1 > num2) {
      return 1
    } else if (num1 < num2) {
      return -1
    }
  }

  return 0
}

export function isPhoneNumFormat(phoneNum){
	const phoneReg = /^((\+|00)86)?1[3-9]\d{9}$/
	return phoneReg.test(phoneNum)
}

export function debounce(func, delay) {
    let timeout; // 用于存储setTimeout返回的ID
    return function(...args) {
        const context = this; // 保存this上下文
        clearTimeout(timeout); // 清除之前的定时器
        timeout = setTimeout(() => {
            func.apply(context, args); // 在延迟后执行func
        }, delay);
    };
}